// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
	 * @desc 保存文章
	 * @return {Promise} []
	 */
  async saveArticleAction() {
    const data = this.post();
    data.shopid = this.shop_userinfo.departmentid;
    data.addtime = Math.round(Date.parse(new Date()) / 1000);
    data.adminid = this.shop_userinfo.id;
    let res;
    if (data.id) {
      res = await this.model('or_weixin_article').where({
        id: data.id
      }).update(data);
    } else {
      res = await this.model('or_weixin_article').add(data);
    }
    return res ? this.success('操作成功') : this.fail('操作失败');
  }

  /*
   * @desc 获取文章列表
   * 
   */
  async getArticleListAction() {
    let filter = this.get();
    filter = JSON.parse(filter.filter);
    const where = {};
    if (filter.times && (filter.times[0] != null && filter.times[1] != null)) {
      const begintime = Math.floor(new Date(filter.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(filter.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400;
      where['w.addtime'] = {'>=': begintime, '<': endtime};
    }
    where['w.shopid'] = this.shop_userinfo.departmentid;
    if (filter.search) {
      where['w.title'] = ['like', '%' + filter.search + '%'];
    }

    const list = await this.model('or_weixin_article')
      .alias('w')
      .field('w.*, a.name')
      .join('think_or_admin a on w.adminid = a.id')
      .where(where)
      .page(filter.pages, filter.limits)
      .order('w.addtime desc')
      .countSelect();
    return this.json(list);
  }

  /*
   * @desc 获取单个文章信息
   * @return {object} 文章信息
   */
  async getArticleInfoAction() {
    const id = this.get().id;
    const article = await this.model('or_weixin_article').where({id: id}).find();
    return this.json(article);
  }

  /*
   * @desc 删除单个文章
   */
  async deleteArticleAction() {
    const id = this.post().id;
    const res = await this.model('or_weixin_article').where({id: id}).delete();
    return res ? this.success('操作成功') : this.fail('操作失败');
  }

  /*
   * @desc 获取文章模板列表
   */
  async getArticleTemplateAction() {
    let filter = JSON.parse(this.post('filter'))

    let list = await this.model('or_template_article')
    .page(filter.currentpage, filter.pagesize)
    .countSelect();

    return this.json(list)
  }

  /*
   * @desc 获取单个文章模板
   */
  async getArticleTemplateInfoAction() {
    const id = this.get().id;
    const article = await this.model('or_template_article').where({id: id}).find();
    return this.json(article);
  }
}
